package com.lemi.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lemi.dao.OutletsMapper;
import com.lemi.dao.RoleMapper;
import com.lemi.dao.UserMapper;
import com.lemi.dao.UserRoleMapper;
import com.lemi.entity.*;
import com.lemi.util.BspEntity;
import com.lemi.util.BspResult;
import com.lemi.util.BspUtils;
import com.lemi.util.Constant;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("user")
public class UserController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Resource
    private OutletsMapper outletsMapper;



    @RequestMapping("list")
    public String list(Model model, BspEntity bspEntity){
        model.addAttribute("bspEntity",bspEntity);
        return "sys/user";
    }

    @RequestMapping("listData")
    @ResponseBody
    public Object listData(BspEntity bspEntity){
        try {
            Example ue = new Example(User.class);
            Example.Criteria criteria = ue.createCriteria();
            criteria.andEqualTo("delFlag",false);

            if(StringUtils.isNotBlank(bspEntity.getName())){
                criteria.andLike("userName","%"+bspEntity.getName()+"%");
            }

            if(StringUtils.isNotBlank(bspEntity.getUseName())){
                criteria.andLike("nickName","%"+bspEntity.getUseName()+"%");
            }

            if(bspEntity.getIsUse()!=null){
                criteria.andEqualTo("isUse",bspEntity.getIsUse());
            }

            if(bspEntity.getStartDate()!=null){
                criteria.andGreaterThanOrEqualTo("createTime",bspEntity.getStartDate());
            }

            if(bspEntity.getEndDate()!=null){
                criteria.andLessThan("createTime", BspUtils.getDayTime(bspEntity.getEndDate(),1));
            }


            PageHelper.startPage(bspEntity.getPage(),bspEntity.getLimit());
            PageHelper.orderBy(bspEntity.getOrderColumn()+" "+bspEntity.getOrderDir());

            List<User> users = userMapper.selectByExample(ue);
            PageInfo<User> orderPageInfo = new PageInfo<>(users);
            bspEntity.setTotal(orderPageInfo.getTotal());
            bspEntity.setListData(users);

            return BspResult.ok("",bspEntity);
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }

    @RequestMapping("toEdit")
    public String toEdit(Model model, BspEntity bspEntity){

        if(bspEntity.getId()!=null){
            Example ue = new Example(User.class);
            ue.createCriteria().andEqualTo("delFlag",false).andEqualTo("id",bspEntity.getId());
            List<User> users = userMapper.selectByExample(ue);
            if(users.size()>0){
                User user = users.get(0);
                List<Role> userRoles = userMapper.getUserRoles(bspEntity);
                Map<Integer, String> roles = new HashMap<>();
                for (Role role:userRoles) {
                    roles.put(role.getId(),role.getRoleName());
                }
                user.setRoleMaps(roles);
                model.addAttribute("user",user);
            }
        }

        Example re = new Example(Role.class);
        re.createCriteria().andEqualTo("delFlag",false).andEqualTo("isUse",1);
        List<Role> roles = roleMapper.selectByExample(re);
        model.addAttribute("roles",roles);

        Example oe = new Example(Outlets.class);
        oe.createCriteria().andEqualTo("delFlag",false);
        List<Outlets> outletses = outletsMapper.selectByExample(oe);
        model.addAttribute("outletses",outletses);

        model.addAttribute("bspEntity",bspEntity);
        return "sys/user-edit";
    }

    @RequestMapping("edit")
    @ResponseBody
    public Object edit(HttpSession session,User user){
        try {

            if(StringUtils.isBlank(user.getUserName()) || StringUtils.isBlank(user.getNickName())){
                return BspResult.err("账号和使用人姓名不能为空！");
            }

            //判断账号是否存在
            Example ue = new Example(User.class);
            Example.Criteria criteria = ue.createCriteria();
            criteria.andEqualTo("delFlag",false).andEqualTo("userName",user.getUserName());
            if(user.getId()!=null){
                criteria.andNotEqualTo("id",user.getId());
            }

            List<User> users = userMapper.selectByExample(ue);
            if(users.size()>0){
                return BspResult.err("账号已存在！");
            }

            String roleIds = user.getRoleIds();
            List<String> roleList = new ArrayList<>();
            if(StringUtils.isNotBlank(roleIds)){
                roleList = Arrays.asList(roleIds.split(","));
            }

            List<UserRole> insertUserRoles = new ArrayList<UserRole>();

            User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);
            Example ure = new Example(UserRole.class);

            if(user.getId()==null){//新增
                user.setCreateTime(new Date());
                user.setCreateName(loginUser.getUserName());
                user.setIsUse(1);
                user.setDelFlag(false);
                user.setVersion(0L);
                userMapper.insert(user);

                for (String roleId:roleList) {
                    insertUserRoles.add(new UserRole(user.getId()+"",roleId,new Date(),loginUser.getUserName()));
                }
            }else{//修改
                user.setUpdateTime(new Date());
                user.setUpdateName(loginUser.getUserName());
                userMapper.updateByPrimaryKeySelective(user);

                ure.clear();
                ure.createCriteria().andEqualTo("delFlag",false).andEqualTo("userId",user.getId());
                List<UserRole> userRoles = userRoleMapper.selectByExample(ure);

                outer:for (String roleId:roleList) {
                    for (UserRole userRole:userRoles) {
                        if(roleId.equals(userRole.getRoleId())){
                            continue outer;
                        }
                    }
                    insertUserRoles.add(new UserRole(user.getId()+"",roleId,new Date(),loginUser.getUserName()));
                }

            }

            if(insertUserRoles.size()>0){
                userRoleMapper.insertBatch(insertUserRoles);
            }

            UserRole userRole = new UserRole();
            userRole.setDelFlag(true);
            userRole.setUpdateTime(new Date());
            userRole.setUpdateName(loginUser.getUserName());
            ure.clear();
            Example.Criteria criteria1 = ure.createCriteria();
            criteria1.andEqualTo("delFlag",false).andEqualTo("userId",user.getId());
            if(roleList.size()>0){
                criteria1.andNotIn("roleId",roleList);
            }
            userRoleMapper.updateByExampleSelective(userRole,ure);

            return BspResult.ok();
        }catch (Exception e){
            e.printStackTrace();
            return BspResult.err(Constant.SERVER_ERR);
        }
    }

    @RequestMapping("isUse")
    public String isUse(HttpSession session,Model model, BspEntity bspEntity){
        if(bspEntity.getId()!=null){
            Example ue = new Example(User.class);
            ue.createCriteria().andEqualTo("delFlag",false).andEqualTo("id",bspEntity.getId());
            List<User> users = userMapper.selectByExample(ue);
            if(users.size()>0){
                User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);

                User user = users.get(0);
                Integer isUse = user.getIsUse();
                user.setIsUse(isUse==1?0:1);
                user.setUpdateTime(new Date());
                user.setUpdateName(loginUser.getUserName());
                userMapper.updateByPrimaryKeySelective(user);
            }
        }
        model.addAttribute("bspEntity",bspEntity);
        return list(model,bspEntity);
    }

    @RequestMapping("pwd")
    public String pwd(HttpSession session,Model model, BspEntity bspEntity){
        if(bspEntity.getId()!=null){
            Example ue = new Example(User.class);
            ue.createCriteria().andEqualTo("delFlag",false).andEqualTo("id",bspEntity.getId());
            List<User> users = userMapper.selectByExample(ue);
            if(users.size()>0){
                User loginUser = (User)session.getAttribute(Constant.SESSION_USER_INFO);

                User user = users.get(0);
                user.setPassword(bspEntity.getPassword());
                user.setUpdateTime(new Date());
                user.setUpdateName(loginUser.getUserName());
                userMapper.updateByPrimaryKeySelective(user);
            }
        }
        model.addAttribute("bspEntity",bspEntity);
        return list(model,bspEntity);
    }

}
